from django.shortcuts import render
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.core.files.storage import default_storage
from django.core.files.base import ContentFile
import cv2
from .forms import UploadFileForm
from PIL import Image,ImageDraw  # 使用Pillow库处理图片
import os
import logging
from onnx_infer.ensemble import Ensembel as CartoonModel
from sightseeing_infer.ensemble import Ensemble as SightSeeingModel
logger = logging.getLogger(__name__)


def get_main_url(requset):
    return render(requset,'main2.html')
class GetConfig:
    def __init__(self,project_name,cartoon_onnx_256,cartoon_onnx_512,detect_onnx):
        self.project_name = project_name
        self.cartoon_onnx_256 = cartoon_onnx_256
        self.cartoon_onnx_512 =cartoon_onnx_512
        self.detect_onnx = detect_onnx

@csrf_exempt
def upload_file(request): 
    if request.method == 'POST' and request.FILES.get('file'):
        style = request.POST["imagestyle"]
        config = GetConfig(
            f'{style}',
            f'onnx_infer/cartoon/weight/best_{style}_weight/generator_best_256.onnx',             
            f'onnx_infer/cartoon/weight/best_{style}_weight/generator_best_512.onnx',  
            f'onnx_infer/detect/weight/version-slim-320_without_postprocessing.onnx')
            
        
        model = CartoonModel('onnx_infer/utils/mask_images/mask1.jpg',config)
        
        
        file = request.FILES['file']
        file_name = default_storage.save(file.name, ContentFile(file.read()))
        file_path = os.path.join(default_storage.location, file_name)

        
        img = model.run2(file_path)
        
      
        processed_file_name = 'processed_' + file_name
        processed_file_path = os.path.join(default_storage.location, processed_file_name)
        cv2.imwrite(processed_file_path,img)
        
        return JsonResponse({'processed_file_url': default_storage.url(processed_file_name)})

    
    return JsonResponse({'error': 'Invalid request'}, status=400)


@csrf_exempt
def upload_file_sightseeing(request):
    if request.method == 'POST' and request.FILES.get('file'):
        style = request.POST["sightseeingstyle"]
        model = SightSeeingModel(f'sightseeing_infer/cartoon/weight/{style}/best_{style}_bg.onnx')
        
        file = request.FILES['file']
        file_name = default_storage.save(file.name,ContentFile(file.read()))
        file_path = os.path.join(default_storage.location,file_name)
        
        img = model.run(file_path)
        processed_file_name = 'processed_' + file_name
        processed_file_path = os.path.join(default_storage.location, processed_file_name)
        cv2.imwrite(processed_file_path,img)
        
        return JsonResponse({'processed_file_url': default_storage.url(processed_file_name)})
        